#include "cJSON/cJSON.h"
#include "log/log.h"
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    // 1. 生成json   
    char *n = "tom";
    int age = 18;
    cJSON *rootObj = cJSON_CreateObject();
    cJSON_AddStringToObject(rootObj, "name", n);
    cJSON_AddNumberToObject(rootObj, "age", age);
    char *json = cJSON_PrintUnformatted(rootObj);
    log_debug("生成json: %s", json);


    // 2. 解析json
    cJSON *rootObj2 = cJSON_Parse(json);
    if (rootObj2==NULL) {
        log_error("解析json失败");
        return -1;
    } 
    cJSON *nameObj = cJSON_GetObjectItem(rootObj2, "name");
    cJSON *ageObj = cJSON_GetObjectItem(rootObj2, "age");
    char *name2 = nameObj->valuestring;
    int age2 = ageObj->valueint;
    log_debug("解析json: name = %s, age = %d", name2, age2);

    // 3. 释放内存
    cJSON_Delete(rootObj);
    cJSON_Delete(rootObj2);
    free(json);

    return 0;
}
